package cn.nfwx.tv.controller;

import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.nfwx.tv.R;
import cn.nfwx.tv.adapter.HotChannelAdapter;
import cn.nfwx.tv.adapter.HotVideoAdapter;
import cn.nfwx.tv.base.BaseDialogFragment;
import cn.nfwx.tv.callback.ResponseListener;
import cn.nfwx.tv.fragment.callback.ActionCallback;
import cn.nfwx.tv.helper.NetworkHelper;
import cn.nfwx.tv.helper.ThreadHelper;
import cn.nfwx.tv.manager.HotColomnManager;
import cn.nfwx.tv.model.Result;
import cn.nfwx.tv.model.TvChannel;
import cn.nfwx.tv.model.TvProgram;
import cn.nfwx.tv.okhttp.CustomOkHttpClient;
import cn.nfwx.tv.util.NetworkUtil;
import cn.nfwx.tv.util.RecyclerViewUtil;
import cn.nfwx.tv.widget.LoadView;
import cn.nfwx.tv.widget.WxLoadmoreView;
import cn.nfwx.tv.widget.WxRefreshView;

/**
 * 热门频道以及热门节目
 * Created by zhouzechao on 2017/11/17.
 */
public class TVHotViewController extends BaseDialogFragment implements View.OnClickListener, OnTabSelectListener, NetworkHelper.NetworkStateListener, LoadView.OnLoadClickListener {

    private static final String TAG = TVHotViewController.class.getSimpleName();

    //private TVHotViewItemClickListener listener;

    private SegmentTabLayout segmentTabLayout;
    private RecyclerView hot_video_recyclerView;
    private TextView tv_cancle_btn;
    //private View.OnClickListener mPositiveListener;
    private TwinklingRefreshLayout trl_hot_vod;
    private LoadView loadView;

    private final static String KEY_HOT = "hot_key";
    private final static String KEY_HOT_POSTION = "key_hot_postion";

    private List<Parcelable> hotLives = new ArrayList<>();

    private HotChannelAdapter mHotChannelAdapter;
    private HotVideoAdapter mHotVideoAdapter;

    private String requestHotColumnListComand, requestIjkHotVideosComand;
    private List<Parcelable> programs = new ArrayList<>();

    private int pageNo = 1;
    private int pageSize = 18;
    private int current;

    private ActionCallback mActionCallback;
    public final static String ACTION_HOT_LIVE = "ACTION_HOT_LIVE";
    public final static String ACTION_HOT_VIDEO = "ACTION_HOT_VIDEO";
    public final static String ACTION_HOT_CLICK = "ACTION_HOT_CLICK";

    public static TVHotViewController newInstance() {
        TVHotViewController fragment = new TVHotViewController();
        return fragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActionCallback = ActionCallback.NONE;
        if (activity instanceof ActionCallback) {
            mActionCallback = (ActionCallback) activity;
        }
    }

    /**
     * 是否填满整个屏幕
     */
    protected boolean isMatchParent() {
        return true;
    }

    protected boolean isOutsideTouchable() {
        return true;
    }

    //是否透明背景
    protected boolean isTranslucentBackground() {
        return true;
    }

    protected boolean isTranslucentStatus() {
        return false;
    }

    protected int getGravity() {
        return Gravity.BOTTOM;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_player_tv_pop;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mActionCallback = ActionCallback.NONE;
        release();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        HorizontalDividerItemDecoration itemDecoration = new HorizontalDividerItemDecoration.Builder(getContext())
                .color(Color.TRANSPARENT)
                .size(60)
                .build();
        mHotChannelAdapter = new HotChannelAdapter(getContext());
        mHotVideoAdapter = new HotVideoAdapter();
        trl_hot_vod = findView(R.id.trl_hot_vod);
        WxRefreshView sinaRefreshView = new WxRefreshView(getContext());
        sinaRefreshView.setArrowResource(R.mipmap.mine_down);
        trl_hot_vod.setHeaderView(sinaRefreshView);
        trl_hot_vod.setBottomView(new WxLoadmoreView(getContext()));

        tv_cancle_btn = findView(R.id.tv_cancle_btn);
        hot_video_recyclerView = findView(R.id.hot_video_recyclerView);
        hot_video_recyclerView.addItemDecoration(itemDecoration);
        segmentTabLayout = findView(R.id.tv_segment_tab);
        String[] titles = {"热门频道", "热门视频"};
        segmentTabLayout.setTabData(titles);

        loadView = new LoadView(getContext());


        initListener();
    }

    private void initListener() {
        mHotChannelAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                dismiss();
                if (mActionCallback != null) {
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("data", (Parcelable) adapter.getData().get(position));
                    bundle.putInt("position", position);
                    mActionCallback.callbackByfragment(ACTION_HOT_LIVE, bundle);
                }
            }
        });
        mHotVideoAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //dismiss();
                if (mActionCallback != null) {
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("data", (Parcelable) adapter.getData().get(position));
                    bundle.putInt("position", position);
                    mActionCallback.callbackByfragment(ACTION_HOT_VIDEO, bundle);
                    dismissAllowingStateLoss();
                }
            }
        });
        segmentTabLayout.setOnTabSelectListener(this);
        tv_cancle_btn.setOnClickListener(this);
        trl_hot_vod.setOnRefreshListener(refreshListener);
        loadView.setOnLoadClickLisener(this);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        hotLives.clear();
        List<Parcelable> liveModels = getArguments().getParcelableArrayList(KEY_HOT);
        current = getArguments().getInt(KEY_HOT_POSTION, 0);


        hotLives.addAll(liveModels);
        segmentTabLayout.setCurrentTab(current);
        bindData(current);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_cancle_btn:
                dismiss();
                break;
        }
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        finisRefreshView();
        CustomOkHttpClient.cancleAll(requestHotColumnListComand);
        CustomOkHttpClient.cancleAll(requestIjkHotVideosComand);
        if (mActionCallback != null) {
            Bundle bundle = new Bundle();
            bundle.putInt("id", tv_cancle_btn.getId());
            mActionCallback.callbackByfragment(ACTION_HOT_CLICK, bundle);
        }
        super.onDismiss(dialog);
    }

    /**
     * ======SegmentTabLayout========
     */
    @Override
    public void onTabSelect(int position) {
        current = position;
        bindData(position);
    }

    @Override
    public void onTabReselect(int position) {

    }

    /**
     * 刷新
     */
    private void refresh() {
        pageNo = 1;
        if (!hotLives.isEmpty()) {
            Parcelable parcelable = hotLives.get(0);
            if (parcelable instanceof TvChannel) {
                requestIjkHotVideosComand = HotColomnManager.requestIjkHotVideos(getContext(), pageNo, pageSize, callback);
            }
        }

    }

    /**
     * 加载
     */
    private void loadmode() {
        pageNo++;
        if (!hotLives.isEmpty()) {
            Parcelable parcelable = hotLives.get(0);
            if (parcelable instanceof TvChannel) {
                requestIjkHotVideosComand = HotColomnManager.requestIjkHotVideos(getContext(), pageNo, pageSize, callback);
            }
        }
    }

    /**
     * 绑定数据
     *
     * @param position
     */
    private void bindData(int position) {
        switch (position) {
            case 0: // 热门频道
                finisRefreshView();
                CustomOkHttpClient.cancleAll(requestHotColumnListComand);
                CustomOkHttpClient.cancleAll(requestIjkHotVideosComand);
                RecyclerViewUtil.setGridLayoutManager(getContext(), hot_video_recyclerView, 4);
                hot_video_recyclerView.setAdapter(mHotChannelAdapter);
                trl_hot_vod.setEnableRefresh(false);
                trl_hot_vod.setEnableLoadmore(false);
                if (loadView.getParent() != null) {
                    trl_hot_vod.removeView(loadView);
                }
                if (hotLives.isEmpty()) {

                } else {
                    mHotChannelAdapter.setNewData(hotLives);
                }
                break;
            case 1: // 热门视频
                trl_hot_vod.setEnableRefresh(true);
                trl_hot_vod.setEnableLoadmore(true);
                RecyclerViewUtil.setGridLayoutManager(getContext(), hot_video_recyclerView, 3);
                hot_video_recyclerView.setAdapter(mHotVideoAdapter);
                if (programs.isEmpty()) {
                    // 加载框
                    if (loadView.getParent() == null) {
                        trl_hot_vod.addView(loadView);
                        loadView.startLoading();
                    }
                    refresh();
                } else { // 防止地址重复
                    List<Parcelable> datas = new ArrayList<>();
                    datas.addAll(programs);
                    mHotVideoAdapter.setNewData(datas);
                }
                break;
        }
    }

    /**
     *  刷新
     */
    RefreshListenerAdapter refreshListener = new RefreshListenerAdapter() {
        @Override
        public void onRefresh(TwinklingRefreshLayout refreshLayout) {
            refresh();
        }

        @Override
        public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
            loadmode();
        }
    };

    /**
     * 数据回调
     */
    ResponseListener callback = new ResponseListener<JSONObject>() {
        @Override
        public void onResponse(final String requestTag, final JSONObject response) {
            ThreadHelper.post(new Runnable() {
                @Override
                public void run() {
                    if (requestTag.equals(requestIjkHotVideosComand)) {
                        Result<List<Parcelable>> result = JSON.parseObject(response.toString(), new TypeReference<Result<List<TvProgram>>>() {
                        }.getType());
                        if (Result.RESULT_SUCCESS.equals(result.getMessage())) {
                            if (pageNo == 1) {
                                programs.clear();
                                programs.addAll(result.getData());
                                mHotVideoAdapter.setNewData(result.getData());
                                // 加载框
                                if (loadView.getParent() != null) {
                                    if (result.getData().isEmpty()) { // 无数据
                                        loadView.stopLoading();
                                        loadView.loadNodata();
                                    } else {
                                        // 有数据
                                        loadView.stopLoading();
                                        trl_hot_vod.removeView(loadView);
                                    }
                                }
                            } else {
                                programs.addAll(result.getData());
                                mHotVideoAdapter.addData(result.getData());
                            }
                        }
                    }
                }
            });
        }

        @Override
        public void onError(String requestTag, final Throwable t) {
            ThreadHelper.post(new Runnable() {
                @Override
                public void run() {
                    if (loadView.getParent() != null) {
                        loadView.stopLoading();
                        loadView.loadError();
                    }
                }
            });
        }

        @Override
        public void onFinish() {
            ThreadHelper.post(new Runnable() {
                @Override
                public void run() {
                    finisRefreshView();
                    if (loadView.isLoading()) {
                        if (loadView.getParent() != null) {
                            trl_hot_vod.removeView(loadView);
                        }
                    }
                }
            });
        }
    };

    /**
     * 刷新刷新布局
     */
    private void finisRefreshView() {
        if (pageNo == 1) {
            trl_hot_vod.finishRefreshing();
        } else {
            trl_hot_vod.finishLoadmore();
        }
    }

    /**
     * 设置数据，放到容器里并从onViewCreated之后再拿出来
     *
     * @param data
     * @param _position
     */
    public void setData(List<? extends Parcelable> data, int _position) {
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList(KEY_HOT, (ArrayList<? extends Parcelable>) data);
        bundle.putInt(KEY_HOT_POSTION, _position);
        this.setArguments(bundle);
    }

    /**
     * 销毁，防止内存泄漏,有请求销毁请求
     */
    public void release() {
        hotLives.clear();
        programs.clear();
        CustomOkHttpClient.cancleAll(requestHotColumnListComand);
        CustomOkHttpClient.cancleAll(requestIjkHotVideosComand);
    }

    @Override
    public void onNetworkChange(int networkType) {
        if (networkType == NetworkUtil.NO_NETWORK) {
            if (loadView.getParent() == null) {
                trl_hot_vod.addView(loadView);
                loadView.netError();
            }
        } else {
            bindData(current);
            if (loadView.getParent() != null) {
                trl_hot_vod.removeView(loadView);
            }
        }
    }

    @Override
    public void onreload() {
        bindData(current);
    }

    @Override
    public void onnext() {

    }
}
